import { Component, OnInit } from '@angular/core'
import { FormBuilder, FormGroup } from '@angular/forms'
import { Observable, BehaviorSubject } from 'rxjs'
import { map, delay, switchMap, tap } from 'rxjs/operators'
import { NzMessageService } from 'ng-zorro-antd'

import { ChannelFormService } from '../../components/channel-form/channel-form.service'
import { I18NService } from '@core'
import { StoreService } from '../../store.service'
import { StoreDataService } from '../../store-data.service'
import { EPaymentBrand } from '@shared/enums'
import { IQRRouteOfStore, StoreCreate } from '@shared/interfaces/store'
import { makeAllControlDirty } from 'app/utils/helpers'
import { Currency } from '@shared/interfaces/common'
import { IChannelMap } from '../../components/channels-switcher/channels-switcher.interface'
import { NewPageAccessor } from '@shared/components/new-page/new-page.interface'
import { IStoreChannelFormOutput } from './qrcode-channel.interface'

@Component({
  selector: 'app-store-new-qrcode-channel',
  templateUrl: './qrcode-channel.component.html',
  styleUrls: ['../../../../shared/styles/new-page-form.less'],
})
export class StoreNewQrcodeChannelComponent implements NewPageAccessor, OnInit {
  constructor(
    public msg: NzMessageService,
    public fb: FormBuilder,
    public storeDataService: StoreDataService,
    private channelFormService: ChannelFormService,
    private storeService: StoreService,
    private i18n: I18NService,
  ) {}

  data: any
  storeFull: StoreCreate
  payload: IQRRouteOfStore[]

  validateForm: FormGroup = this.fb.group({})

  insCode$: Observable<string>
  storeCurrencies$: Observable<Currency[]>
  channelsMap$: Observable<IChannelMap>
  loadingSubject = new BehaviorSubject(true)
  isLoading$ = this.loadingSubject.asObservable().pipe(delay(0))

  ngOnInit() {
    this.insCode$ = this.storeDataService.value$.pipe(map((store: StoreCreate) => store.store.common.insCode))

    this.storeCurrencies$ = this.storeDataService.value$.pipe(
      map((store: StoreCreate) => store.store.common.currencies),
    )

    this.channelsMap$ = this.storeDataService.value$.pipe(
      switchMap(full => {
        this.storeFull = full

        return this.storeService.getAcquirerQRChannels(full.store.common.insCode).pipe(
          map(channels => {
            const temp = new Map<EPaymentBrand, IQRRouteOfStore>()
            full.qrChannels.forEach(ch => {
              temp.set(ch.paymentBrand, ch)
            })

            const mp: IChannelMap = {}
            for (const ch of channels) {
              const brand = ch.paymentBrand || ch.chanCode
              const route = temp.has(brand) ? temp.get(brand) : null
              mp[brand] = route
            }

            return mp
          }),
        )
      }),
      tap(() => this.loadingSubject.next(false)),
    )
  }

  checkValid(): boolean {
    if (this.validateForm.controls.TRU) {
      if (this.validateForm.controls.TRU.get('authOnline').value && !this.validateForm.controls.TRU.get('payNearby').value) {
        this.validateForm.controls.TRU.get('shopID').setValue('223')
      }
      if (this.validateForm.controls.TRU.get('chanCode').value === 'TRU'
      && !this.validateForm.controls.TRU.get('authOnline').value && !this.validateForm.controls.TRU.get('payNearby').value) {
        this.msg.error(this.trans('VALID.PAY.MEATHOD.NOE'))
        return false
      }
    }
    if (this.validateForm.valid) {
      if (this.validateForm.controls.TRU) {
        if (this.validateForm.controls.TRU.get('authOnline').value && !this.validateForm.controls.TRU.get('payNearby').value) {
          this.validateForm.controls.TRU.get('shopID').setValue('')
        }
      }
      this.pushDataToStore()
      this.msg.success(this.trans('GENERAL.NOTIFICATION.VALIDATION_SUCCESS'))
      return true
    }

    makeAllControlDirty(this.validateForm)
    this.msg.error(this.trans('GENERAL.NOTIFICATION.VALIDATION_FAIL'))
    return false
  }

  pushDataToStore(): void {
    const channelsFromForm: IStoreChannelFormOutput[] = Object.keys(this.validateForm.value).map(
      ch => this.validateForm.value[ch],
    )
    const channels = channelsFromForm.map(chan => this.channelFormService.convertToIQRRouteOfStore(chan))
    this.storeFull.qrChannels = channels
    this.storeDataService.updateValue(this.storeFull)
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
